from hurryoff.db import *
from hurryoff.db import DBSession
from hurryoff import log
import parsers
import googleAPIService as gapi

logger = log.module_logger("TrainService")

def addTrain(train):
    session = DBSession()
    with session.begin(subtransactions=True):
        return session.add(train)

def parseStops(stops_json):
    for index, stop_json in enumerate(stops_json):
        station = parseStation(stop_json["station"]["name"])
        arrival = parsers.parseTime(stop_json["arrival"])
        departure = parsers.parseTime(stop_json["departure"])
        yield Stop(station, index, arrival, departure)

def parseStation(stationName):
    countryCode = gapi.getCountryCodeByLocation(stationName)
    station = getStation(stationName, countryCode)
    if station is None:
        logger.info("Create station with name '%s'" % stationName)
        station = Station(stationName, countryCode)
        coordinates = gapi.getGeoCoordinates(stationName, countryCode)
        if coordinates is not None:
            station.lng, station.lat = coordinates[0], coordinates[1]
    return station

def getStation(stationName, countryCode):
    session = DBSession()
    with session.begin(subtransactions=True):
        return session.query(Station) \
            .filter(Station.name == stationName) \
            .filter(Station.countryCode == countryCode) \
            .first()